package log

import (
	"fmt"
	"io"
	"log"
	"os"

	mlog "gitee.com/yrwy/go-log"
	mio "gitee.com/yrwy/msgo/pkg/io"
)

type Writer struct {
	logger *log.Logger
	w      io.Closer
}

func NewWriter(logfile string, flag int) *Writer {
	if logfile != "" {
		f, err := os.OpenFile(logfile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
		if err == nil {
			ws := make(mio.Writers, 0)
			ws = append(ws, f, os.Stdout)
			return &Writer{log.New(ws, "", flag), f}
		}
		log.Println(err)
	}
	log.SetFlags(flag)
	return &Writer{log.Default(), nil}
}

func (x *Writer) Close() error {
	if x != nil && x.w != nil {
		w := x.w
		x.w = nil
		x.logger = log.Default()
		return w.Close()
	}
	return nil
}

func getLevel(lv mlog.Level) string {
	switch lv {
	case mlog.DEBUG:
		return "[D]"
	case mlog.INFO:
		return "[I]"
	case mlog.WARN:
		return "[W]"
	case mlog.ERROR:
		return "[E]"
	case mlog.FATAL:
		return "[F]"
	}
	return "[T]"
}

// 日志输出全局接口
func (x Writer) Log(lv mlog.Level, args ...any) error {
	return x.LogDepth(2, lv, args...)
}

func (x Writer) Logf(lv mlog.Level, format string, args ...any) error {
	return x.LogDepthf(2, lv, format, args...)
}

func (x Writer) Logr(lv mlog.Level, r io.Reader) error {
	return x.LogDepthr(2, lv, r)
}

// calldepth从0开始计算
func (x Writer) LogDepth(calldepth int, lv mlog.Level, args ...any) error {
	if x.logger != nil {
		return x.logger.Output(calldepth+1, getLevel(lv)+fmt.Sprintln(args...))
	}
	return log.Output(calldepth+1, getLevel(lv)+fmt.Sprintln(args...))
}

func (x Writer) LogDepthf(calldepth int, lv mlog.Level, format string, args ...any) error {
	return x.LogDepth(calldepth+1, lv, fmt.Sprintf(format, args...))
}

func (x Writer) LogDepthr(calldepth int, lv mlog.Level, r io.Reader) error {
	buf, err := io.ReadAll(r)
	if err != nil {
		return err
	}
	return x.LogDepth(calldepth+1, lv, string(buf))
}
